package cn.ad.server.common.utils;

import java.io.ByteArrayInputStream;
import java.io.DataInputStream;
import java.io.IOException;
import java.util.Formatter;

import org.apache.commons.codec.digest.DigestUtils;
import org.apache.commons.lang3.StringUtils;

public class CodecUtils {

	private static final String HMAC_SHA1_ALGORITHM = "HmacSHA1";

	public static String toSha1(String source) {
		if (StringUtils.isEmpty(source))
			return "";
		return DigestUtils.sha1Hex(source);
	}

	public static String toMD5(String source) {
		if (StringUtils.isEmpty(source))
			return "";
		return DigestUtils.md5Hex(source);
	}

	static String toHexString(byte[] bytes) {
		Formatter formatter = new Formatter();
		for (byte b : bytes) {
			formatter.format("%02x", b);
		}
		String r = formatter.toString();
		formatter.close();
		return r;
	}

	// public static String calculateRFC2104HMAC(String data, String key)
	// throws SignatureException, NoSuchAlgorithmException, InvalidKeyException
	// {
	// SecretKeySpec signingKey = new SecretKeySpec(key.getBytes(),
	// HMAC_SHA1_ALGORITHM);
	// Mac mac = Mac.getInstance(HMAC_SHA1_ALGORITHM);
	// mac.init(signingKey);
	// return toHexString(mac.doFinal(data.getBytes()));
	// }
	//
	// public static double unencryptePrice(String source, String ekey, String
	// ikey) {
	//
	// try {
	// if (StringUtils.isBlank(source) || StringUtils.isBlank(ekey) ||
	// StringUtils.isBlank(ikey))
	// return 0;
	// DoubleClickCrypto.Keys keys = new DoubleClickCrypto.Keys(new
	// SecretKeySpec(ekey.getBytes(), "HmacSHA1"),
	// new SecretKeySpec(ikey.getBytes(), "HmacSHA1"));
	// DoubleClickCrypto.Price crypto = new DoubleClickCrypto.Price(keys);
	// return crypto.decodePriceValue(source);
	// } catch (Exception e) {
	// return 0;
	// }
	// }

	public static long decryptWinPrice(String encPrice, String ekey, String ikey) {
		if (StringUtils.isBlank(encPrice) || StringUtils.isBlank(ekey) || StringUtils.isBlank(ikey))
			return 0;
		byte[] bytes = Decrypter.decryptSafeWebStringToByte(encPrice, ekey, ikey);
		DataInputStream dis = new DataInputStream(new ByteArrayInputStream(bytes));
		long value = 0;
		try {
			value = dis.readLong();
		} catch (IOException e) {
			e.printStackTrace();
		}
		return value;
	}

	public static void main(String args[]) throws Exception {
		String source = "3HbAJ1cBAABVPgVmTiY7ZQW6xU9DeZ3Zqnmr6Q";
		String ekey = "NwyO3gRmiArLApAurovSw4efD50W4joG";
		String ikey = "OMmijgQzLuf6PQylJD9z3hanPq6IiYZA";
		long price2 = decryptWinPrice(source, ekey, ikey);
		System.out.println("解密后的价格为：" + price2);
	}

	// public static void main(String args[]) {
	// String source = "2vSxklYBAABHMkNJKj1nPEw8pUBh5D6nKalZ5w";
	// String ekey = "NwyO3gRmiArLApAurovSw4efD50W4joG";
	// String ikey = "OMmijgQzLuf6PQylJD9z3hanPq6IiYZA";
	// System.out.println(unencryptePrice(source, ekey, ikey));
	// }

}
